package com.newgrand.service.impl;/*
 *@authot liugz
 *  @date 2023/9/19 14:48
 */

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.newgrand.domain.model.CWBackModel;
import com.newgrand.domain.model.I8ReturnModel;
import com.newgrand.service.CntMSRServer;
import com.newgrand.utils.HttpClientUtil;
import com.newgrand.utils.JSONValid;
import com.newgrand.utils.TimeUtils;
import com.newgrand.utils.security.Md5Utils;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class CntMSRImpl implements CntMSRServer {

    @Value("${cw.tokenUrl}")
    private String tokenUrl;

    //合同基本信息
    @Value("${cw.CNT.SR.addUrl}")
    private String addUrl;
    @Value("${cw.CNT.SR.editUrl}")
    private String editUrl;
    @Value("${cw.CNT.SR.delUrl}")
    private String delUrl;

    //计量与收款节点信息 新增、修改接口地址
    @Value("${cw.CNT.SR.addSKJDUrl}")
    private String addSKJDUrl;
    @Value("${cw.CNT.SR.editSKJDUrl}")
    private String editSKJDUrl;
    @Value("${cw.CNT.SR.delSKJDUrl}")
    private String delSKJDUrl;

    //合同签约方信息 新增、修改接口地址
    @Value("${cw.CNT.SR.addJYBUrl}")
    private String addJYBUrl;
    @Value("${cw.CNT.SR.editJYBUrl}")
    private String editJYBUrl;
    @Value("${cw.CNT.SR.delJYBUrl}")
    private String delJYBUrl;

    //合同清单信息 新增、修改接口地址
    @Value("${cw.CNT.SR.addCntDUrl}")
    private String addCntDUrl;
    @Value("${cw.CNT.SR.editCntDUrl}")
    private String editCntDUrl;
    @Value("${cw.CNT.SR.delCntDUrl}")
    private String delCntDUrl;

    //最小核算项目
    @Value("${cw.CNT.SR.addMinProjUrl}")
    private String addMinProjUrl;
    @Value("${cw.CNT.SR.editMinProjUrl}")
    private String editMinProjUrl;
    @Value("${cw.CNT.SR.delMinProjUrl}")
    private String delMinProjUrl;

    @Value("${cw.appID}")
    private String appID;
    @Value("${cw.appKEY}")
    private String appKEY;
    @Value("${cw.appSecret}")
    private String appSecret;
    private final JdbcTemplate jdbcTemplate;
    private final Logger logger = LoggerFactory.getLogger(getClass());
    //  收入合同新增接口
    @Override
    public I8ReturnModel<String> sendCntM1(String phId) {
        try {
            List<Map<String, Object>> dataList = jdbcTemplate.queryForList("select * from CntM1_view where phid = ?", phId);
            if (dataList.isEmpty()) {
                return I8ReturnModel.success("无数据需要推送");
            }
            I8ReturnModel<String> returnModel = getToken();
            if (!returnModel.getIsOk()) {
                return I8ReturnModel.errorCode("401", "获取Token失败");
            }
            CWBackModel cwBackModel = JSONObject.parseObject(returnModel.getData(), CWBackModel.class);
            if (!"200".equals(cwBackModel.getCode())) {
                return I8ReturnModel.errorCode("401", cwBackModel.getMsg());
            }

            String sendUrl = addUrl;
            Map<String, Object> dataMap = dataList.get(0);
            if ("1".equals(dataMap.get("report_status")) || "2".equals(dataMap.get("report_status"))) {
                dataMap.put("report_status", "-2");
                return sendCntM1Edit(dataMap, phId);
            }else{dataMap.put("report_status", "-1");}

            HashMap<String, Object> map = new HashMap<>();
            map.put("dataSourceId", "469912437211140096");
            map.put("modelId", "475401302239744082");
            map.put("data", dataMap);
            String body = JSON.toJSONString(map);
            logger.info("phid=" + phId + "，收入合同基本信息推送报文：" + body);
            String tyStamp = String.valueOf(System.currentTimeMillis());
            String tySign = Md5Utils.hash(tyStamp + body + appSecret);
            Map<String, String> headers = new HashMap<>();
            headers.put("TYDTC_APP_TOKEN", cwBackModel.getData());
            sendUrl += "?tyStamp=" + tyStamp + "&tySign=" + tySign;
            returnModel = HttpClientUtil.sendPost(sendUrl, headers, body, "POST");
            logger.info("phid=" + phId + "，收入合同基本信息推送返回结果：" + returnModel.getData());
            if (returnModel.getIsOk() && JSONValid.isJSON2(returnModel.getData())) {
                cwBackModel = JSONObject.parseObject(returnModel.getData(), CWBackModel.class);
                if ("200".equals(cwBackModel.getCode())) {
                    jdbcTemplate.update("update pcm3_cnt_m set user_report_status = '1', user_report_date = ?, user_report_result = '收入合同基本信息新增推送成功' where phid = ?", TimeUtils.getDateStr(), phId);
                    sendCntM1SKJD(phId);//计量与收款节点信息
                    sendCntM1JYBBatch(phId); //合同签约方信息
                    sendCntM1D(phId);   //合同清单信息
                    sendCntM1MinProj(phId); //最小核算项目
                    return I8ReturnModel.success(cwBackModel.getMsg());
                }
                throw new RuntimeException(cwBackModel.getMsg());
            }
            throw new RuntimeException(returnModel.getMessage());
        } catch (Exception ex) {
            String msg = "推送失败:" + ex.getMessage();
            jdbcTemplate.update("update pcm3_cnt_m set  user_report_date = ?, user_report_result = ? where phid = ?", TimeUtils.getDateStr(), msg, phId);
            return I8ReturnModel.errorCode("500", ex.getMessage());
        }
    }

    @Override
    public I8ReturnModel<String> sendCntM1Delete(String phId) {
        try {
            List<Map<String, Object>> dataList = jdbcTemplate.queryForList("select * from CntM1_view where phid = ?", phId);
            if (dataList.isEmpty()) {
                return I8ReturnModel.success("暂无数据需删除");
            }
            Map<String, Object> dataMap = dataList.get(0);
            String sendUrl = delUrl;
            dataMap.put("report_status", "-3");//赋值为中台待删除状态
            I8ReturnModel<String> returnModel = getToken();
            if (!returnModel.getIsOk()) {
                return I8ReturnModel.errorCode("401", "获取Token失败");
            }
            CWBackModel cwBackModel = JSONObject.parseObject(returnModel.getData(), CWBackModel.class);
            if (!"200".equals(cwBackModel.getCode())) {
                return I8ReturnModel.errorCode("401", cwBackModel.getMsg());
            }
            HashMap<String, Object> map = new HashMap<>();
            map.put("dataSourceId", "469912437211140096");
            map.put("modelId", "475401302239744082");
            Map<String,Object> conditionsMap = new HashMap<>();
            Map<String,Object> conditionValuesMap = new HashMap<>();
            conditionsMap.put("internal_id","=");
            conditionValuesMap.put("internal_id",dataMap.get("internal_id"));
            map.put("conditions", conditionsMap);
            map.put("conditionValues", conditionValuesMap);

            String body = JSON.toJSONString(map);
            logger.info("phid=" + phId + "，合同基本信息删除推送报文：" + body);
            String tyStamp = String.valueOf(System.currentTimeMillis());
            String tySign = Md5Utils.hash(tyStamp + body + appSecret);
            Map<String, String> headers = new HashMap<>();
            headers.put("TYDTC_APP_TOKEN", cwBackModel.getData());
            sendUrl += "?tyStamp=" + tyStamp + "&tySign=" + tySign;
            returnModel = HttpClientUtil.sendPost(sendUrl, headers, body, "POST");
            logger.info("phid=" + phId + "，合同基本信息删除推送返回结果：" + returnModel.getData());
            if (returnModel.getIsOk() && JSONValid.isJSON2(returnModel.getData())) {
                cwBackModel = JSONObject.parseObject(returnModel.getData(), CWBackModel.class);
                if ("200".equals(cwBackModel.getCode())) {
                    jdbcTemplate.update("update pcm3_cnt_m set user_report_status = '3', user_report_date = ?, user_report_result = '收入合同基本信息删除推送成功' where phid = ?", TimeUtils.getDateStr(), phId);
                    sendCntM1SKJDDelete(phId); //收款阶段删除
                    sendCntM1JYBBatchDelete(phId);  //合同签约方删除
                    sendCntM1DDelete(phId); //合同清单删除
                    sendCntM1MinProjDelete(phId); // 删除最小核算项目
                    return I8ReturnModel.success(cwBackModel.getMsg());
                }
                throw new RuntimeException(cwBackModel.getMsg());
            }
            throw new RuntimeException(returnModel.getMessage());
        } catch (Exception ex) {
            String msg = "推送失败:" + ex.getMessage();
            jdbcTemplate.update("update pcm3_cnt_m set user_report_date = ?, user_report_result = ? where phid = ?", TimeUtils.getDateStr(), msg, phId);
            return I8ReturnModel.errorCode("500", ex.getMessage());
        }
    }

    //  收入合同修改接口
    public I8ReturnModel<String> sendCntM1Edit(Map<String, Object> dataMap,String phid) {
        try {
            I8ReturnModel<String> returnModel = getToken();
            if (!returnModel.getIsOk()) {
                return I8ReturnModel.errorCode("401", "获取Token失败");
            }
            CWBackModel cwBackModel = JSONObject.parseObject(returnModel.getData(), CWBackModel.class);
            if (!"200".equals(cwBackModel.getCode())) {
                return I8ReturnModel.errorCode("401", cwBackModel.getMsg());
            }
            String sendUrl = editUrl;
            HashMap<String, Object> map = new HashMap<>();
            Map<String,Object> conditionsMap = new HashMap<>();
            Map<String,Object> conditionValuesMap = new HashMap<>();
            conditionsMap.put("internal_id","=");
            conditionValuesMap.put("internal_id",dataMap.get("internal_id"));
            map.put("values", dataMap);
            map.put("conditions", conditionsMap);
            map.put("conditionValues", conditionValuesMap);
            map.put("dataSourceId", "469912437211140096");
            map.put("modelId", "475401302239744082");

            String body = JSON.toJSONString(map);
            logger.info("phid=" + phid + "，收入合同基本信息修改推送报文：" + body);
            String tyStamp = String.valueOf(System.currentTimeMillis());
            String tySign = Md5Utils.hash(tyStamp + body + appSecret);
            Map<String, String> headers = new HashMap<>();
            headers.put("TYDTC_APP_TOKEN", cwBackModel.getData());
            sendUrl += "?tyStamp=" + tyStamp + "&tySign=" + tySign;
            returnModel = HttpClientUtil.sendPost(sendUrl, headers, body, "POST");
            logger.info("phid=" + phid + "，收入合同基本信息修改推送返回结果：" + returnModel.getData());
            if (returnModel.getIsOk() && JSONValid.isJSON2(returnModel.getData())) {
                cwBackModel = JSONObject.parseObject(returnModel.getData(), CWBackModel.class);
                if ("200".equals(cwBackModel.getCode())) {
                    jdbcTemplate.update("update pcm3_cnt_m set user_report_status = '2', user_report_date = ?, user_report_result = '收入合同基本信息修改推送成功' where phid = ?", TimeUtils.getDateStr(), phid);
                    sendCntM1SKJD(phid);//计量与收款节点信息
                    sendCntM1JYBBatch(phid); //合同签约方信息
                    sendCntM1D(phid);   //合同清单信息
                    sendCntM1MinProj(phid); //最小核算项目
                    return I8ReturnModel.success(cwBackModel.getMsg());
                }
                throw new RuntimeException(cwBackModel.getMsg());
            }
            throw new RuntimeException(returnModel.getMessage());
        } catch (Exception ex) {
            jdbcTemplate.update("update pcm3_cnt_m set  user_report_date = ?, user_report_result = '收入合同基本信息修改推送失败' where phid = ?", TimeUtils.getDateStr(), phid);
            return I8ReturnModel.errorCode("500", ex.getMessage());
        }
    }

    //计量与收款节点信息新增、修改
    public I8ReturnModel<String> sendCntM1SKJD(String phId) {
        try {
            List<Map<String, Object>> dataList = jdbcTemplate.queryForList("select * from SKJD_VIEW where phid = ?", phId);
            if (dataList.isEmpty()) {
                return I8ReturnModel.success("无数据需要推送");
            }
            I8ReturnModel<String> returnModel = getToken();
            if (!returnModel.getIsOk()) {
                return I8ReturnModel.errorCode("401", "获取Token失败");
            }
            CWBackModel cwBackModel = JSONObject.parseObject(returnModel.getData(), CWBackModel.class);
            if (!"200".equals(cwBackModel.getCode())) {
                return I8ReturnModel.errorCode("401", cwBackModel.getMsg());
            }
            boolean sta = true;//true表示新增||false表示修改
            String sendUrl = addSKJDUrl;
            Map<String, Object> dataMap = dataList.get(0);
            if ("1".equals(dataMap.get("report_status")) || "2".equals(dataMap.get("report_status"))) {
                sta = false;
                dataMap.put("report_status", "-2");//赋值为中台修改状态
                sendUrl = editSKJDUrl;
            }else{dataMap.put("report_status", "-1");}//删除的重修推送新增接口

            HashMap<String, Object> map = new HashMap<>();
            map.put("dataSourceId", "469912437211140096");
            map.put("modelId", "475401302239744082");
//            新增、修改状态参数不同，单独处理 sta：true表示新增||false表示修改
            if(sta){
                map.put("data", dataMap);
            }else{
                Map<String,Object> conditionsMap = new HashMap<>();
                Map<String,Object> conditionValuesMap = new HashMap<>();
                conditionsMap.put("internal_id","=");
                conditionValuesMap.put("internal_id",dataMap.get("internal_id"));
                map.put("values", dataMap);
                map.put("conditions", conditionsMap);
                map.put("conditionValues", conditionValuesMap);
            }

            String body = JSON.toJSONString(map);
            logger.info("phid=" + phId + "，收入合同计量与收款节点信息推送报文：" + body);
            String tyStamp = String.valueOf(System.currentTimeMillis());
            String tySign = Md5Utils.hash(tyStamp + body + appSecret);
            Map<String, String> headers = new HashMap<>();
            headers.put("TYDTC_APP_TOKEN", cwBackModel.getData());
            sendUrl += "?tyStamp=" + tyStamp + "&tySign=" + tySign;
            returnModel = HttpClientUtil.sendPost(sendUrl, headers, body, "POST");
            logger.info("phid=" + phId + "，收入合同计量与收款节点信息推送返回结果：" + returnModel.getData());
            if (returnModel.getIsOk() && JSONValid.isJSON2(returnModel.getData())) {
                cwBackModel = JSONObject.parseObject(returnModel.getData(), CWBackModel.class);
                if ("200".equals(cwBackModel.getCode())) {
                    String report_rusult = "收入合同计量与收款节点信息新增推送成功";//推送结果
                    String report_status = "1";
                    if(!sta){report_rusult = "收入合同计量与收款节点信息修改推送成功";report_status = "2";}
                    jdbcTemplate.update("update pcm3_cnt_m set user_skjd_report_status = ?, user_skjd_report_date = ?, user_skjd_report_rusult = ? where phid = ?",report_status, TimeUtils.getDateStr(),report_rusult, phId);
                    return I8ReturnModel.success(cwBackModel.getMsg());
                }
                throw new RuntimeException(cwBackModel.getMsg());
            }
            throw new RuntimeException(returnModel.getMessage());
        } catch (Exception ex) {
            String msg = "推送失败:" + ex.getMessage();
            jdbcTemplate.update("update pcm3_cnt_m set  user_skjd_report_date = ?, user_skjd_report_rusult = ? where phid = ?", TimeUtils.getDateStr(), msg, phId);
            return I8ReturnModel.errorCode("500", ex.getMessage());
        }
    }

    @Override
    public I8ReturnModel<String> sendCntM1SKJDDelete(String phId) {
        try {
            List<Map<String, Object>> dataList = jdbcTemplate.queryForList("select * from SKJD_VIEW where phid = ?", phId);
            if (dataList.isEmpty()) {
                return I8ReturnModel.success("暂无数据需删除");
            }
            Map<String, Object> dataMap = dataList.get(0);
            String sendUrl = delSKJDUrl;
            dataMap.put("report_status", "-3");//赋值为中台待删除状态
            I8ReturnModel<String> returnModel = getToken();
            if (!returnModel.getIsOk()) {
                return I8ReturnModel.errorCode("401", "获取Token失败");
            }
            CWBackModel cwBackModel = JSONObject.parseObject(returnModel.getData(), CWBackModel.class);
            if (!"200".equals(cwBackModel.getCode())) {
                return I8ReturnModel.errorCode("401", cwBackModel.getMsg());
            }
            HashMap<String, Object> map = new HashMap<>();
            map.put("dataSourceId", "469912437211140096");
            map.put("modelId", "475401302239744082");
            Map<String,Object> conditionsMap = new HashMap<>();
            Map<String,Object> conditionValuesMap = new HashMap<>();
            conditionsMap.put("internal_id","=");
            conditionValuesMap.put("internal_id",dataMap.get("internal_id"));
            map.put("conditions", conditionsMap);
            map.put("conditionValues", conditionValuesMap);

            String body = JSON.toJSONString(map);
            logger.info("phid=" + phId + "，计量与收款节点信息删除推送报文：" + body);
            String tyStamp = String.valueOf(System.currentTimeMillis());
            String tySign = Md5Utils.hash(tyStamp + body + appSecret);
            Map<String, String> headers = new HashMap<>();
            headers.put("TYDTC_APP_TOKEN", cwBackModel.getData());
            sendUrl += "?tyStamp=" + tyStamp + "&tySign=" + tySign;
            returnModel = HttpClientUtil.sendPost(sendUrl, headers, body, "POST");
            logger.info("phid=" + phId + "，合同计量与收款节点信息删除推送返回结果：" + returnModel.getData());
            if (returnModel.getIsOk() && JSONValid.isJSON2(returnModel.getData())) {
                cwBackModel = JSONObject.parseObject(returnModel.getData(), CWBackModel.class);
                if ("200".equals(cwBackModel.getCode())) {
                    jdbcTemplate.update("update pcm3_cnt_m set user_skjd_report_status = '3', user_skjd_report_date = ?, user_skjd_report_rusult = '收入合同计量与收款节点信息删除推送成功' where phid = ?", TimeUtils.getDateStr(), phId);
                    return I8ReturnModel.success(cwBackModel.getMsg());
                }
                throw new RuntimeException(cwBackModel.getMsg());
            }
            throw new RuntimeException(returnModel.getMessage());
        } catch (Exception ex) {
            String msg = "推送失败:" + ex.getMessage();
            jdbcTemplate.update("update pcm3_cnt_m set user_skjd_report_date = ?, user_skjd_report_rusult = ? where phid = ?", TimeUtils.getDateStr(), msg, phId);
            return I8ReturnModel.errorCode("500", ex.getMessage());
        }
    }

    //合同签约方信息 收入合同甲乙丙方信息新增、修改
    public I8ReturnModel<String> sendCntM1JYBBatch(String phId) {
        List<Map<String, Object>> dataListJ = jdbcTemplate.queryForList("select * from CntM1_JF_VIEW where cntid = ?",phId);
        sendCntM1JYB(dataListJ);
        List<Map<String, Object>> dataListY = jdbcTemplate.queryForList("select * from CntM1_YF_VIEW where cntid = ?",phId);
        sendCntM1JYB(dataListY);
        List<Map<String, Object>> dataListB = jdbcTemplate.queryForList("select * from CntM1_BF_VIEW where cntid = ? ",phId);
        sendCntM1JYB(dataListB);
        return I8ReturnModel.success();
    }

    @Override
    public I8ReturnModel<String> sendCntM1JYBBatchDelete(String phId) {
        List<Map<String, Object>> dataListJ = jdbcTemplate.queryForList("select * from CntM1_JF_VIEW where cntid = ?",phId);
        sendCntM1JYBDelete(dataListJ);
        List<Map<String, Object>> dataListY = jdbcTemplate.queryForList("select * from CntM1_YF_VIEW where cntid = ?",phId);
        sendCntM1JYBDelete(dataListY);
        List<Map<String, Object>> dataListB = jdbcTemplate.queryForList("select * from CntM1_BF_VIEW where cntid = ? ",phId);
        sendCntM1JYBDelete(dataListB);
        return I8ReturnModel.success();
    }

    public I8ReturnModel<String> sendCntM1JYBDelete(List<Map<String, Object>> dataList) {
        try {
            if (dataList.isEmpty()) {
                return I8ReturnModel.success("无数据需要推送");
            }
            I8ReturnModel<String> returnModel = getToken();
            if (!returnModel.getIsOk()) {
                return I8ReturnModel.errorCode("401", "获取Token失败");
            }
            CWBackModel cwBackModel = JSONObject.parseObject(returnModel.getData(), CWBackModel.class);
            if (!"200".equals(cwBackModel.getCode())) {
                return I8ReturnModel.errorCode("401", cwBackModel.getMsg());
            }
            String sendUrl = delJYBUrl;
            Map<String, Object> dataMap = dataList.get(0);
            HashMap<String, Object> map = new HashMap<>();
            map.put("dataSourceId", "469912437211140096");
            map.put("modelId", "475401302239744080");
            Map<String,Object> conditionsMap = new HashMap<>();
            Map<String,Object> conditionValuesMap = new HashMap<>();
            conditionsMap.put("internal_id","=");
            conditionValuesMap.put("internal_id",dataMap.get("internal_id"));
            map.put("conditions", conditionsMap);
            map.put("conditionValues", conditionValuesMap);

            String body = JSON.toJSONString(map);
            logger.info("phid=" + dataMap.get("cntid") + "，收入合同签约方信息删除推送报文：" + body);
            String tyStamp = String.valueOf(System.currentTimeMillis());
            String tySign = Md5Utils.hash(tyStamp + body + appSecret);
            Map<String, String> headers = new HashMap<>();
            headers.put("TYDTC_APP_TOKEN", cwBackModel.getData());
            sendUrl += "?tyStamp=" + tyStamp + "&tySign=" + tySign;
            returnModel = HttpClientUtil.sendPost(sendUrl, headers, body, "POST");
            logger.info("phid=" + dataMap.get("cntid") + "，收入合同签约方信息删除推送返回结果：" + returnModel.getData());
            if (returnModel.getIsOk() && JSONValid.isJSON2(returnModel.getData())) {
                cwBackModel = JSONObject.parseObject(returnModel.getData(), CWBackModel.class);
                if ("200".equals(cwBackModel.getCode())) {
                    if("1".equals(dataMap.get("contr_role_cd"))){ //推送甲方
                        jdbcTemplate.update("update pcm3_cnt_m set user_jf_report_status = '3', user_jf_report_date = ?, user_jf_report_result = '甲方信息删除成功' where phid = ?", TimeUtils.getDateStr(), dataMap.get("cntid"));
                    }else if("2".equals(dataMap.get("contr_role_cd"))){  //推送乙方
                        jdbcTemplate.update("update pcm3_cnt_m set user_yf_report_status = '3', user_yf_report_date = ?, user_yf_report_result = '乙方信息删除成功' where phid = ?", TimeUtils.getDateStr(), dataMap.get("cntid"));
                    }else if("3".equals(dataMap.get("contr_role_cd"))){  //推送丙方
                        jdbcTemplate.update("update pcm3_cnt_m set user_bf_report_status = '3', user_bf_report_date = ?, user_bf_report_result = '丙方信息删除成功' where phid = ?", TimeUtils.getDateStr(), dataMap.get("cntid"));
                    }
                    return I8ReturnModel.success(cwBackModel.getMsg());
                }
                throw new RuntimeException(cwBackModel.getMsg());
            }
            throw new RuntimeException(returnModel.getMessage());
        } catch (Exception ex) {
            String msg = "推送失败:" + ex.getMessage();
            Map<String, Object> dataMap = dataList.get(0);
            if("1".equals(dataMap.get("contr_role_cd"))){ //推送甲方
                jdbcTemplate.update("update pcm3_cnt_m set  user_jf_report_date = ?, user_jf_report_result = ? where phid = ?", TimeUtils.getDateStr(), msg, dataMap.get("cntid"));
            }else if("2".equals(dataMap.get("contr_role_cd"))){  //推送乙方
                jdbcTemplate.update("update pcm3_cnt_m set  user_yf_report_date = ?, user_yf_report_result = ? where phid = ?", TimeUtils.getDateStr(), msg, dataMap.get("cntid"));
            }else if("3".equals(dataMap.get("contr_role_cd"))){  //推送丙方
                jdbcTemplate.update("update pcm3_cnt_m set  user_bf_report_date = ?, user_bf_report_result = ? where phid = ?", TimeUtils.getDateStr(), msg, dataMap.get("cntid"));
            }
            return I8ReturnModel.errorCode("500", ex.getMessage());
        }
    }

    public I8ReturnModel<String> sendCntM1JYB(List<Map<String, Object>> dataList) {
        try {
            if (dataList.isEmpty()) {
                return I8ReturnModel.success("无数据需要推送");
            }
            I8ReturnModel<String> returnModel = getToken();
            if (!returnModel.getIsOk()) {
                return I8ReturnModel.errorCode("401", "获取Token失败");
            }
            CWBackModel cwBackModel = JSONObject.parseObject(returnModel.getData(), CWBackModel.class);
            if (!"200".equals(cwBackModel.getCode())) {
                return I8ReturnModel.errorCode("401", cwBackModel.getMsg());
            }
            boolean sta = true;//true表示新增||false表示修改
            String sendUrl = addJYBUrl;
            Map<String, Object> dataMap = dataList.get(0);
            if ("1".equals(dataMap.get("report_status")) || "2".equals(dataMap.get("report_status"))) {
                sta = false;
                dataMap.put("report_status", "-2");//赋值为中台修改状态
                sendUrl = editJYBUrl;
            }else{dataMap.put("report_status", "-1");}//删除的重修推送新增接口

            HashMap<String, Object> map = new HashMap<>();
            map.put("dataSourceId", "469912437211140096");
            map.put("modelId", "475401302239744080");
//            新增、修改状态参数不同，单独处理 sta：true表示新增||false表示修改
            if(sta){
                map.put("data", dataMap);
            }else{
                Map<String,Object> conditionsMap = new HashMap<>();
                Map<String,Object> conditionValuesMap = new HashMap<>();
                conditionsMap.put("internal_id","=");
                conditionValuesMap.put("internal_id",dataMap.get("internal_id"));
                map.put("values", dataMap);
                map.put("conditions", conditionsMap);
                map.put("conditionValues", conditionValuesMap);
            }

            String body = JSON.toJSONString(map);
            logger.info("phid=" + dataMap.get("cntid") + "，收入合同签约方信息推送报文：" + body);
            String tyStamp = String.valueOf(System.currentTimeMillis());
            String tySign = Md5Utils.hash(tyStamp + body + appSecret);
            Map<String, String> headers = new HashMap<>();
            headers.put("TYDTC_APP_TOKEN", cwBackModel.getData());
            sendUrl += "?tyStamp=" + tyStamp + "&tySign=" + tySign;
            returnModel = HttpClientUtil.sendPost(sendUrl, headers, body, "POST");
            logger.info("phid=" + dataMap.get("cntid") + "，收入合同签约方信息推送返回结果：" + returnModel.getData());
            if (returnModel.getIsOk() && JSONValid.isJSON2(returnModel.getData())) {
                cwBackModel = JSONObject.parseObject(returnModel.getData(), CWBackModel.class);
                if ("200".equals(cwBackModel.getCode())) {
                    String report_rusult = "签约方信息新增推送成功";//推送结果
                    String report_status = "1";
                    if(!sta){report_rusult = "签约方信息修改推送成功";report_status = "2";}
                    if("1".equals(dataMap.get("contr_role_cd"))){ //推送甲方
                        jdbcTemplate.update("update pcm3_cnt_m set user_jf_report_status = ?, user_jf_report_date = ?, user_jf_report_result = ? where phid = ?",report_status, TimeUtils.getDateStr(),report_rusult, dataMap.get("cntid"));
                    }else if("2".equals(dataMap.get("contr_role_cd"))){  //推送乙方
                        jdbcTemplate.update("update pcm3_cnt_m set user_yf_report_status = ?, user_yf_report_date = ?, user_yf_report_result = ? where phid = ?",report_status, TimeUtils.getDateStr(),report_rusult, dataMap.get("cntid"));
                    }else if("3".equals(dataMap.get("contr_role_cd"))){  //推送丙方
                        jdbcTemplate.update("update pcm3_cnt_m set user_bf_report_status = ?, user_bf_report_date = ?, user_bf_report_result = ? where phid = ?",report_status, TimeUtils.getDateStr(),report_rusult, dataMap.get("cntid"));
                    }
                    return I8ReturnModel.success(cwBackModel.getMsg());
                }
                throw new RuntimeException(cwBackModel.getMsg());
            }
            throw new RuntimeException(returnModel.getMessage());
        } catch (Exception ex) {
            String msg = "推送失败:" + ex.getMessage();
            Map<String, Object> dataMap = dataList.get(0);
            if("1".equals(dataMap.get("contr_role_cd"))){ //推送甲方
                jdbcTemplate.update("update pcm3_cnt_m set  user_jf_report_date = ?, user_jf_report_result = ? where phid = ?", TimeUtils.getDateStr(), msg, dataMap.get("cntid"));
            }else if("2".equals(dataMap.get("contr_role_cd"))){  //推送乙方
                jdbcTemplate.update("update pcm3_cnt_m set  user_yf_report_date = ?, user_yf_report_result = ? where phid = ?", TimeUtils.getDateStr(), msg, dataMap.get("cntid"));
            }else if("3".equals(dataMap.get("contr_role_cd"))){  //推送丙方
                jdbcTemplate.update("update pcm3_cnt_m set  user_bf_report_date = ?, user_bf_report_result = ? where phid = ?", TimeUtils.getDateStr(), msg, dataMap.get("cntid"));
            }
            return I8ReturnModel.errorCode("500", ex.getMessage());
        }
    }

    //合同汇总清单
    public I8ReturnModel<String> sendCntM1D(String phId) {
        try {
            List<Map<String, Object>> dataList = jdbcTemplate.queryForList("select * from CntM1_D_VIEW where phid = ?",phId);
            if (dataList.isEmpty()) {
                return I8ReturnModel.success("无数据需要推送");
            }
            I8ReturnModel<String> returnModel = getToken();
            if (!returnModel.getIsOk()) {
                return I8ReturnModel.errorCode("401", "获取Token失败");
            }
            CWBackModel cwBackModel = JSONObject.parseObject(returnModel.getData(), CWBackModel.class);
            if (!"200".equals(cwBackModel.getCode())) {
                return I8ReturnModel.errorCode("401", cwBackModel.getMsg());
            }
            boolean sta = true;//true表示新增||false表示修改
            String sendUrl = addCntDUrl;
            Map<String, Object> dataMap = dataList.get(0);
            if ("1".equals(dataMap.get("report_status")) || "2".equals(dataMap.get("report_status"))) {
                sta = false;
                dataMap.put("report_status", "-2");//赋值为中台修改状态
                sendUrl = editCntDUrl;
            }else{dataMap.put("report_status", "-1");}//删除的重修推送新增接口

            HashMap<String, Object> map = new HashMap<>();
            map.put("dataSourceId", "469912437211140096");
            map.put("modelId", "475401302239744072");
//            新增、修改状态参数不同，单独处理 sta：true表示新增||false表示修改
            if(sta){
                map.put("data", dataMap);
            }else{
                Map<String,Object> conditionsMap = new HashMap<>();
                Map<String,Object> conditionValuesMap = new HashMap<>();
                conditionsMap.put("internal_id","=");
                conditionValuesMap.put("internal_id",dataMap.get("internal_id"));
                map.put("values", dataMap);
                map.put("conditions", conditionsMap);
                map.put("conditionValues", conditionValuesMap);
            }

            String body = JSON.toJSONString(map);
            logger.info("phid=" + phId + "，收入合同签约方信息推送报文：" + body);
            String tyStamp = String.valueOf(System.currentTimeMillis());
            String tySign = Md5Utils.hash(tyStamp + body + appSecret);
            Map<String, String> headers = new HashMap<>();
            headers.put("TYDTC_APP_TOKEN", cwBackModel.getData());
            sendUrl += "?tyStamp=" + tyStamp + "&tySign=" + tySign;
            returnModel = HttpClientUtil.sendPost(sendUrl, headers, body, "POST");
            logger.info("phid=" + phId + "，合同清单信息推送返回结果：" + returnModel.getData());
            if (returnModel.getIsOk() && JSONValid.isJSON2(returnModel.getData())) {
                cwBackModel = JSONObject.parseObject(returnModel.getData(), CWBackModel.class);
                if ("200".equals(cwBackModel.getCode())) {
                    String report_rusult = "合同清单信息新增推送成功";//推送结果
                    String report_status = "1";
                    if(!sta){report_rusult = "合同清单信息修改推送成功";report_status = "2";}
                        jdbcTemplate.update("update pcm3_cnt_m set user_qd_report_status = ?, user_qd_report_date = ?, user_qd_report_result = ? where phid = ?",report_status ,TimeUtils.getDateStr(),report_rusult, phId);
                    return I8ReturnModel.success(cwBackModel.getMsg());
                }
                throw new RuntimeException(cwBackModel.getMsg());
            }
            throw new RuntimeException(returnModel.getMessage());
        } catch (Exception ex) {
            String msg = "推送失败:" + ex.getMessage();
            jdbcTemplate.update("update pcm3_cnt_m set  user_qd_report_date = ?, user_qd_report_result = ? where phid = ?", TimeUtils.getDateStr(), msg, phId);

            return I8ReturnModel.errorCode("500", ex.getMessage());
        }
    }

    @Override
    public I8ReturnModel<String> sendCntM1DDelete(String phId) {
        try {
            List<Map<String, Object>> dataList = jdbcTemplate.queryForList("select * from CntM1_D_VIEW where phid = ?", phId);
            if (dataList.isEmpty()) {
                return I8ReturnModel.success("暂无数据需删除");
            }
            Map<String, Object> dataMap = dataList.get(0);
            String sendUrl = delCntDUrl;
            dataMap.put("report_status", "-3");//赋值为中台待删除状态
            I8ReturnModel<String> returnModel = getToken();
            if (!returnModel.getIsOk()) {
                return I8ReturnModel.errorCode("401", "获取Token失败");
            }
            CWBackModel cwBackModel = JSONObject.parseObject(returnModel.getData(), CWBackModel.class);
            if (!"200".equals(cwBackModel.getCode())) {
                return I8ReturnModel.errorCode("401", cwBackModel.getMsg());
            }
            HashMap<String, Object> map = new HashMap<>();
            map.put("dataSourceId", "469912437211140096");
            map.put("modelId", "475401302239744072");
            Map<String,Object> conditionsMap = new HashMap<>();
            Map<String,Object> conditionValuesMap = new HashMap<>();
            conditionsMap.put("internal_id","=");
            conditionValuesMap.put("internal_id",dataMap.get("internal_id"));
            map.put("conditions", conditionsMap);
            map.put("conditionValues", conditionValuesMap);

            String body = JSON.toJSONString(map);
            logger.info("phid=" + phId + "，合同汇总清单删除推送报文：" + body);
            String tyStamp = String.valueOf(System.currentTimeMillis());
            String tySign = Md5Utils.hash(tyStamp + body + appSecret);
            Map<String, String> headers = new HashMap<>();
            headers.put("TYDTC_APP_TOKEN", cwBackModel.getData());
            sendUrl += "?tyStamp=" + tyStamp + "&tySign=" + tySign;
            returnModel = HttpClientUtil.sendPost(sendUrl, headers, body, "POST");
            logger.info("phid=" + phId + "，合同汇总清单删除推送返回结果：" + returnModel.getData());
            if (returnModel.getIsOk() && JSONValid.isJSON2(returnModel.getData())) {
                cwBackModel = JSONObject.parseObject(returnModel.getData(), CWBackModel.class);
                if ("200".equals(cwBackModel.getCode())) {
                    jdbcTemplate.update("update pcm3_cnt_m set user_qd_report_status = '3', user_qd_report_date = ?, user_qd_report_result = '收入合同合同汇总清单删除推送成功' where phid = ?", TimeUtils.getDateStr(), phId);
                    return I8ReturnModel.success(cwBackModel.getMsg());
                }
                throw new RuntimeException(cwBackModel.getMsg());
            }
            throw new RuntimeException(returnModel.getMessage());
        } catch (Exception ex) {
            String msg = "推送失败:" + ex.getMessage();
            jdbcTemplate.update("update pcm3_cnt_m set user_qd_report_date = ?, user_qd_report_result = ? where phid = ?", TimeUtils.getDateStr(), msg, phId);
            return I8ReturnModel.errorCode("500", ex.getMessage());
        }
    }


    //最小核算项目
    public I8ReturnModel<String> sendCntM1MinProj(String phId) {
        try {
            List<Map<String, Object>> dataList = jdbcTemplate.queryForList("select * from CntM1_MIN_PROJ_VIEW where phid = ?",phId);
            if (dataList.isEmpty()) {
                return I8ReturnModel.success("无数据需要推送");
            }
            I8ReturnModel<String> returnModel = getToken();
            if (!returnModel.getIsOk()) {
                return I8ReturnModel.errorCode("401", "获取Token失败");
            }
            CWBackModel cwBackModel = JSONObject.parseObject(returnModel.getData(), CWBackModel.class);
            if (!"200".equals(cwBackModel.getCode())) {
                return I8ReturnModel.errorCode("401", cwBackModel.getMsg());
            }
            boolean sta = true;//true表示新增||false表示修改
            String sendUrl = addMinProjUrl;
            Map<String, Object> dataMap = dataList.get(0);
            if ("1".equals(dataMap.get("report_status")) || "2".equals(dataMap.get("report_status"))) {
                sta = false;
                dataMap.put("report_status", "-2");//赋值为中台修改状态
                sendUrl = editMinProjUrl;
            }else{dataMap.put("report_status", "-1");}//删除的重修推送新增接口
            HashMap<String, Object> map = new HashMap<>();
            map.put("dataSourceId", "469912437211140096");
            map.put("modelId", "492749593302405120");
//            新增、修改状态参数不同，单独处理 sta：true表示新增||false表示修改
            if(sta){
                map.put("data", dataMap);
            }else{
                Map<String,Object> conditionsMap = new HashMap<>();
                Map<String,Object> conditionValuesMap = new HashMap<>();
                conditionsMap.put("internal_id","=");
                conditionValuesMap.put("internal_id",dataMap.get("internal_id"));
                map.put("values", dataMap);
                map.put("conditions", conditionsMap);
                map.put("conditionValues", conditionValuesMap);
            }

            String body = JSON.toJSONString(map);
            logger.info("phid=" + phId + "，收入合同最小核算项目信息推送报文：" + body);
            String tyStamp = String.valueOf(System.currentTimeMillis());
            String tySign = Md5Utils.hash(tyStamp + body + appSecret);
            Map<String, String> headers = new HashMap<>();
            headers.put("TYDTC_APP_TOKEN", cwBackModel.getData());
            sendUrl += "?tyStamp=" + tyStamp + "&tySign=" + tySign;
            returnModel = HttpClientUtil.sendPost(sendUrl, headers, body, "POST");
            logger.info("phid=" + phId + "，收入合同最小核算项目信息推送返回结果：" + returnModel.getData());
            if (returnModel.getIsOk() && JSONValid.isJSON2(returnModel.getData())) {
                cwBackModel = JSONObject.parseObject(returnModel.getData(), CWBackModel.class);
                if ("200".equals(cwBackModel.getCode())) {
                    String report_rusult = "收入合同最小核算项目信息新增推送成功";//推送结果
                    String report_status = "1";
                    if(!sta){report_rusult = "收入合同最小核算项目信息修改推送成功";report_status = "2";}
                    jdbcTemplate.update("update pcm3_cnt_m set user_min_proj_report_status = ?, user_min_proj_report_date = ?, user_min_proj_report_result = ? where phid = ?",report_status ,TimeUtils.getDateStr(),report_rusult, phId);
                    return I8ReturnModel.success(cwBackModel.getMsg());
                }
                throw new RuntimeException(cwBackModel.getMsg());
            }
            throw new RuntimeException(returnModel.getMessage());
        } catch (Exception ex) {
            String msg = "推送失败:" + ex.getMessage();
            jdbcTemplate.update("update pcm3_cnt_m set  user_min_proj_report_date = ?, user_min_proj_report_result = ? where phid = ?", TimeUtils.getDateStr(), msg, phId);

            return I8ReturnModel.errorCode("500", ex.getMessage());
        }
    }

    public I8ReturnModel<String> sendCntM1MinProjDelete(String phId) {
        try {
            List<Map<String, Object>> dataList = jdbcTemplate.queryForList("select * from CntM1_MIN_PROJ_VIEW where phid = ?", phId);
            if (dataList.isEmpty()) {
                return I8ReturnModel.success("暂无数据需删除");
            }
            Map<String, Object> dataMap = dataList.get(0);
            String sendUrl = delMinProjUrl;
            dataMap.put("report_status", "-3");//赋值为中台待删除状态
            I8ReturnModel<String> returnModel = getToken();
            if (!returnModel.getIsOk()) {
                return I8ReturnModel.errorCode("401", "获取Token失败");
            }
            CWBackModel cwBackModel = JSONObject.parseObject(returnModel.getData(), CWBackModel.class);
            if (!"200".equals(cwBackModel.getCode())) {
                return I8ReturnModel.errorCode("401", cwBackModel.getMsg());
            }
            HashMap<String, Object> map = new HashMap<>();
            map.put("dataSourceId", "469912437211140096");
            map.put("modelId", "492749593302405120");
            Map<String,Object> conditionsMap = new HashMap<>();
            Map<String,Object> conditionValuesMap = new HashMap<>();
            conditionsMap.put("internal_id","=");
            conditionValuesMap.put("internal_id",dataMap.get("internal_id"));
            map.put("conditions", conditionsMap);
            map.put("conditionValues", conditionValuesMap);

            String body = JSON.toJSONString(map);
            logger.info("phid=" + phId + "，外部收入合同删除推送报文：" + body);
            String tyStamp = String.valueOf(System.currentTimeMillis());
            String tySign = Md5Utils.hash(tyStamp + body + appSecret);
            Map<String, String> headers = new HashMap<>();
            headers.put("TYDTC_APP_TOKEN", cwBackModel.getData());
            sendUrl += "?tyStamp=" + tyStamp + "&tySign=" + tySign;
            returnModel = HttpClientUtil.sendPost(sendUrl, headers, body, "POST");
            logger.info("phid=" + phId + "，外部收入合同删除推送返回结果：" + returnModel.getData());
            if (returnModel.getIsOk() && JSONValid.isJSON2(returnModel.getData())) {
                cwBackModel = JSONObject.parseObject(returnModel.getData(), CWBackModel.class);
                if ("200".equals(cwBackModel.getCode())) {
                    jdbcTemplate.update("update pcm3_cnt_m set user_min_proj_report_status = '3', user_min_proj_report_date = ?, user_min_proj_report_result = '收入合同合同汇总清单删除推送成功' where phid = ?", TimeUtils.getDateStr(), phId);
                    return I8ReturnModel.success(cwBackModel.getMsg());
                }
                throw new RuntimeException(cwBackModel.getMsg());
            }
            throw new RuntimeException(returnModel.getMessage());
        } catch (Exception ex) {
            String msg = "推送失败:" + ex.getMessage();
            jdbcTemplate.update("update pcm3_cnt_m set user_min_proj_report_date = ?, user_min_proj_report_result = ? where phid = ?", TimeUtils.getDateStr(), msg, phId);
            return I8ReturnModel.errorCode("500", ex.getMessage());
        }
    }


    //  收入合同批量推送接口
    @Async("asyncServiceExecutor")
    @Override
    public I8ReturnModel<String> sendCntM1Batch() {
        List<Map<String, Object>> dataList = jdbcTemplate.queryForList("select * from CntM1_view");
        for (Map<String, Object> item : dataList) {
            sendCntM1(String.valueOf(item.get("phid")));
        }
        return I8ReturnModel.success();
    }





    public I8ReturnModel<String> getToken() {
        Map<String, String> map = new HashMap<>();
        map.put("TYDTC_APP_ID", appID);
        map.put("TYDTC_APP_KEY", appKEY);
        return HttpClientUtil.sendPost(tokenUrl, map, "", "GET");
    }
}
